package com.ljc.controller;

import com.alibaba.druid.support.logging.Log;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljc.dto.Result;
import com.ljc.entity.CollegeUsersSum;
import com.ljc.entity.User;
import com.ljc.service.UserService;
import com.ljc.util.JWTUtil;
import com.ljc.vo.UserSearch;
import javafx.beans.binding.ObjectExpression;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public Map<String, Object> login(@RequestBody User user) {
        HashMap<String, Object> result = new HashMap<>();
        log.info("用户名：" + user.getName() + " 密码：" + user.getPassword());
        try {
            User userDB = userService.login(user);
            result.put("status", true);
            result.put("msg", "认证成功");

            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(userDB.getId()));
            payload.put("name", user.getName());
            String token = JWTUtil.getToken(payload);
            result.put("token", token);


        } catch (Exception e) {
            result.put("status", false);
            result.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("test")
    public Map<String, Object> test() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", true);
        map.put("msg", "请求成功");
        return map;
    }

    @RequestMapping("getUsers")
    public Result getUsers(HttpServletRequest request,
                           @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(name = "pageSize", defaultValue = "2") int pageSize) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        log.info("get users(deanId={}):", id);
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findByDeanId(Integer.valueOf(id));
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        result.setMsg("查询成功").setStatus(1).setData(userPageInfo);
        return result;
    }

    @RequestMapping("getCollegeUserSum")
    public Result getCollegeUsersSum(HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        log.info("get College usersSum(deanId={}):", id);
        List<CollegeUsersSum> userList = userService.getCollegeUserSum(Integer.valueOf(id));
        result.setMsg("查询成功").setStatus(1).setData(userList);
        return result;
    }

    @RequestMapping("searchUser")
    public Result searchUser(HttpServletRequest request, @RequestBody UserSearch userSearch) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        userSearch.setDeanId(Integer.valueOf(id));
        log.info("search user(search={}):", userSearch);
        PageHelper.startPage(userSearch.getPageNum(), userSearch.getPageSize());
        List<User> userList = userService.searchUser(userSearch);
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        result.setMsg("查询成功").setStatus(1).setData(userPageInfo);
        return result;
    }

    @RequestMapping("addUser")
    public Result addUser(HttpServletRequest request, @RequestBody User user) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        user.setDeanId(Integer.valueOf(id));
        try {
            userService.addUser(user);
            log.info("add user(search={}):", user);
            result.setStatus(1).setMsg("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(0).setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("getOne")
    public Result getOne(@RequestParam int userId) {
        Result result = new Result();
        User user = userService.getOne(userId);
        result.setStatus(1).setMsg("获取用户信息成功").setData(user);
        return result;
    }

    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody User user) {
        Result result = new Result();
        try {
            userService.updateUser(user);
            log.info("update user:[{}]", user);
            result.setStatus(1).setMsg("修改成功");
        } catch (Exception e) {
            result.setStatus(0).setMsg("修改失败");
        }
        return result;
    }

    @RequestMapping("deleteUser")
    public Result deleteUser(@RequestParam int userId) {
        Result result = new Result();
        try {
            userService.deleteUser(userId);
            result.setStatus(1).setMsg("删除成功");
        } catch (Exception e) {
            result.setStatus(0).setMsg("删除失败");
        }
        return result;
    }

    @RequestMapping("getCollegeName")
    public Result getCollegeName(HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        String collegeName = userService.getCollegeNameByUserId(Integer.valueOf(id));
        result.setStatus(1).setMsg("获取成功").setData(collegeName);
        return result;
    }

    @RequestMapping("getInfo")
    public Result getInfo(HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("accessToken");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        User user = userService.getOne(Integer.valueOf(id));
        result.setData(user).setMsg("获取个人信息成功").setStatus(1);
        return result;
    }
}
